<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useSubmissionHook } from "./utils/hook";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Download from "@iconify-icons/ep/download";
import View from "@iconify-icons/ep/view";
import SubmissionDetailModal from "@/views/cafuc/submit/submission/submission-detail-modal.vue";
import SubmissionExportFilesModal from "./submission-export-files-modal.vue";
import { SubmissionPageResponse } from "@/api/performance/submission";
import { getAllUsersSimpleApi, type UserSimpleDTO } from "@/api/system/user";

/** 组件name最好和菜单表中的router_name一致 */
defineOptions({
  name: "submissionDataView"
});

const tableRef = ref();
const searchFormRef = ref();
const route = useRoute();

const {
  searchFormParams,
  pageLoading,
  exportLoading,
  columns,
  dataList,
  pagination,
  defaultSort,
  mainCategoryOptions,
  subCategoryOptions,
  itemCategoryOptions,
  onSearch,
  resetForm,
  onSortChanged,
  asyncExportSubmission,
  getSubmissionList,
  handleMainCategoryChange,
  handleSubCategoryChange
} = useSubmissionHook();

const detailModalVisible = ref(false);
const detailRow = ref<SubmissionPageResponse>();
function openDetailDialog(row: SubmissionPageResponse) {
  detailRow.value = row;
  detailModalVisible.value = true;
}

const exportFilesModalVisible = ref(false);
function openExportFilesDialog() {
  exportFilesModalVisible.value = true;
}

const allUsers = ref<UserSimpleDTO[]>([]);
const userOptions = ref<UserSimpleDTO[]>([]);

async function fetchAllUsersSimple() {
  try {
    const { data } = await getAllUsersSimpleApi();
    allUsers.value = data || [];
    userOptions.value = allUsers.value;
  } catch (error) {
    console.error(error);
  }
}

function remoteSearchUsers(query: string) {
  const q = (query || "").trim();
  if (!q) {
    userOptions.value = allUsers.value;
    return;
  }
  const lower = q.toLowerCase();
  userOptions.value = allUsers.value.filter(user => {
    return (
      (user.nickname || "").toLowerCase().includes(lower) ||
      (user.deptName || "").toLowerCase().includes(lower)
    );
  });
}

function getUserLabel(user: UserSimpleDTO) {
  const name = user.nickname || "";
  const dept = user.deptName || "";
  return dept ? `${name}（${dept}）` : name;
}

function handleReset() {
  const formEl = searchFormRef.value;
  if (!formEl) return;
  resetForm(formEl, tableRef);
}

// 定义审核级别选项
const auditLevelOptions = [
  { label: "非审核状态", value: 0 },
  { label: "待一审", value: 1 },
  { label: "待二审", value: 2 },
  { label: "待三审", value: 3 },
  { label: "已完成", value: 4 }
];

// 定义状态选项
const statusOptions = [
  { label: "待提交", value: "DRAFT" },
  { label: "审核中", value: "PENDING_AUDIT" },
  { label: "已驳回", value: "REJECTED" },
  { label: "已批准", value: "APPROVED" }
];

// 设置表格行的类名（用于标识项目负责人不等于得分人的行）
function getRowClassName({ row }: { row: SubmissionPageResponse }) {
  if (row.owner && row.creatorId && row.owner !== row.creatorId) {
    return "row-owner-different";
  }
  return "";
}

onMounted(async () => {
  await fetchAllUsersSimple();
  
  // 从 URL 参数读取 owner（得分人）并设置到查询参数
  const owner = route.query.owner;
  if (owner) {
    searchFormParams.owner = Number(owner);
  }
  
  // 统一执行一次查询（无论是否有 URL 参数）
  onSearch(tableRef);
});

</script>

<template>
  <div class="main">
    <el-form
      ref="searchFormRef"
      :inline="true"
      :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="序号" prop="id">
        <el-input
          v-model="searchFormParams.id"
          placeholder="请输入序号"
          clearable
          class="!w-[100px]"
        />
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="searchFormParams.title"
          placeholder="请输入标题"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="考核年度" prop="assessmentYear">
        <el-input
          v-model="searchFormParams.assessmentYear"
          placeholder="请输入考核年度"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select
          v-model="searchFormParams.status"
          placeholder="请选择状态"
          clearable
          class="!w-[180px]"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="主类别" prop="mainCategory">
        <el-select
          v-model="searchFormParams.mainCategory"
          placeholder="请选择主类别"
          clearable
          class="!w-[180px]"
          @change="handleMainCategoryChange"
        >
          <el-option
            v-for="item in mainCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="子类别" prop="subCategory">
        <el-select
          v-model="searchFormParams.subCategory"
          placeholder="请选择子类别"
          clearable
          class="!w-[180px]"
          :disabled="!searchFormParams.mainCategory"
          @change="handleSubCategoryChange"
        >
          <el-option
            v-for="item in subCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目类别" prop="itemCategory">
        <el-select
          v-model="searchFormParams.itemCategory"
          placeholder="请选择项目类别"
          clearable
          class="!w-[180px]"
          :disabled="!searchFormParams.subCategory"
        >
          <el-option
            v-for="item in itemCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="当前审核级别" prop="currentAuditLevel">
        <el-select
          v-model="searchFormParams.currentAuditLevel"
          placeholder="请选择当前审核级别"
          clearable
          class="!w-[200px]"
        >
          <el-option
            v-for="item in auditLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="得分人" prop="owner">
        <el-select
          v-model="searchFormParams.owner"
          filterable
          remote
          reserve-keyword
          placeholder="搜索并选择用户"
          :remote-method="remoteSearchUsers"
          clearable
          class="!w-[200px]"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="getUserLabel(item)"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="pageLoading"
          @click="onSearch(tableRef)"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="handleReset">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="绩效上报总览" :columns="columns" @refresh="onSearch">
      <template #buttons>
        <el-button 
          type="primary" 
          :loading="exportLoading"
          @click="asyncExportSubmission"
        >
          生成表格文件
        </el-button>
        <el-button 
          type="primary" 
          @click="openExportFilesDialog"
        >
          下载文件
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          border
          ref="tableRef"
          align-whole="center"
          showOverflowTooltip
          table-layout="auto"
          :loading="pageLoading"
          :size="size"
          adaptive
          :data="dataList"
          :columns="dynamicColumns"
          :default-sort="defaultSort"
          :pagination="pagination"
          :paginationSmall="size === 'small' ? true : false"
          :row-class-name="getRowClassName"
          :header-cell-style="{
            background: 'var(--el-table-row-hover-bg-color)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="getSubmissionList"
          @page-current-change="getSubmissionList"
          @sort-change="onSortChanged"
        >
          <template #title="{ row }">
            <el-button
              link
              type="primary"
              @click="openDetailDialog(row)"
            >
              {{ row.title }}
            </el-button>
          </template>
          <template #operation="{ row }">
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(View)"
              @click="openDetailDialog(row)"
            >
              详情
            </el-button>
          </template>
        </pure-table>
      </template>
    </PureTableBar>

    <submission-detail-modal
      v-model="detailModalVisible"
      :row="detailRow"
    />

    <submission-export-files-modal
      v-model="exportFilesModalVisible"
    />
  </div>
</template>

<style scoped lang="scss">
::deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

// 去掉单元格两边的边框线
::deep(.el-table) {
  td {
    border-left: none !important;
    border-right: none !important;
  }

  th {
    border-left: none !important;
    border-right: none !important;
  }
}

// 项目负责人不等于得分人的行样式（灰色标识）
::deep(.row-owner-different) {
  background-color: rgba(158, 158, 158, 0.1) !important;

  &:hover {
    background-color: rgba(158, 158, 158, 0.15) !important;
  }
}
</style>
